package com.passioneffect.layoutflow {
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.geom.Point;
	
	import com.passioneffect.adapter.ContentMovieClipAdapter;
	import com.passioneffect.collection.Collection;
	import com.passioneffect.collection.Iterator;
	import com.passioneffect.layout.Layout;	

	/**
	 * @author Passion Effect
	 */
	public class ListLayoutFlow implements LayoutFlow{

		public function layoutFlow(layout:Layout,viewList:Collection,items:Collection,container:DisplayObjectContainer,placeFunc:Function) : void {
			
			var startIndex : int = layout.getStartIndex();
			var endIndex : int = layout.getEndIndex();
			
			var mc : MovieClip;
			var adapter : ContentMovieClipAdapter;
			var clearList : Collection = viewList.clone();
			
			var p : Point;
			
			for(var i : int = startIndex;i <= endIndex;i++) {
				
				adapter = ContentMovieClipAdapter(items.getItemAt(i));
				if(!adapter)break;
				p = layout.draw(i);
				
				if(p) {
					mc = MovieClip(adapter.getMovieClip({x:p.x, y:p.y}));
					placeFunc(mc, p);
				}else {
					mc = MovieClip(adapter.getMovieClip());					
				}
				
				if(!viewList.contains(adapter)) {
					//item not in view list, add it
					viewList.addItem(adapter);
					container.addChild(mc);
					mc.visible = true;
				}else {
					//item should stay in view list
					clearList.removeItem(adapter);
				}
			}
			
			//remove items that no need but in view list
			var itr : Iterator = clearList.iterator();
			while(itr.hasNext()) {
				adapter = ContentMovieClipAdapter(itr.next());
				adapter.removeMovieClip();
				viewList.removeItem(adapter);
			}
		}
	}
}
